package com.xmall.order.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xmall.order.define.dict.AfterSaleStatusEnum;
import com.xmall.define.dict.OrderStatusEnum;
import com.xmall.define.base.ResultCode;
import com.xmall.order.define.dto.OrderExpressDto;
import com.xmall.exception.XmallException;
import com.xmall.order.define.request.express.OrderExpressUpdateRequest;
import com.xmall.order.entity.OrderExpress;
import com.xmall.order.mapper.OrderExpressMapper;
import com.xmall.order.service.IOrderExpressService;
import com.xmall.order.service.IOrderRefundService;
import com.xmall.order.service.IOrderService;
import com.xmall.order.utils.ConvertUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * 物流信息 服务实现类
 */
@Service
public class OrderExpressServiceImpl extends ServiceImpl<OrderExpressMapper, OrderExpress> implements IOrderExpressService {

    @Resource
    private IOrderService orderService;

    @Resource
    private IOrderRefundService orderRefundService;

    /**
     * 根据订单ID查询详情
     */
    @Override
    public OrderExpressDto infoByOrderId(Long orderId) {
        OrderExpress entity = this.getOne(new QueryWrapper<OrderExpress>().eq("order_id", orderId));
        return null != entity ? ConvertUtils.ExpressModule.INSTANCE.toDto(entity) : null;
    }

    /**
     * 发货
     */
    @Transactional
    @Override
    public void consignOrder(OrderExpressUpdateRequest request) {
        Long orderId = request.getOrderId();
        if(orderRefundService.hasUnhandledRefund(orderId)) {
            throw new XmallException(ResultCode.ORDER_CONSIGN_ERROR);
        }

        this.save(ConvertUtils.ExpressModule.INSTANCE.toEntity(request));
        orderService.updateOrderStatusStrict(orderId, OrderStatusEnum.WAIT_CONSIGN, OrderStatusEnum.WAIT_RECEIVE);

        // 设置售后状态
        orderService.setOrderAfterSaleStatus(orderId, AfterSaleStatusEnum.VALID);
        orderService.setOrderItemAfterSaleStatusByOrderId(orderId, AfterSaleStatusEnum.VALID);
    }

    /**
     * 编辑
     */
    @Override
    public void update(OrderExpressUpdateRequest request) {
        OrderExpress entity = ConvertUtils.ExpressModule.INSTANCE.toEntity(request);
        this.updateById(entity);
    }
}
